package com.xxx.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IP地址工具类
 * 
 * 
 * 
 */
public class IpUtil {

	private static final Logger logger = LoggerFactory.getLogger(IpUtil.class);

	private IpUtil() {

	}

	/**
	 * 取到当前机器的真实IP地址
	 */
	public static String getIp() {
		List<String> ips = getIps(); // 获取当前机器所有IP地址
		String hostIp = collectionToDelimitedString(ips, ",");
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (hostIp != null && hostIp.length() > 15 && hostIp.indexOf(',') >= 0) { // "***.***.***.***".length() = 15
			hostIp = hostIp.substring(0, hostIp.indexOf(','));
		}
		return hostIp;
	}

	private static List<String> getIps() {
		List<String> ips = new ArrayList<>();
		try {
			Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = netInterfaces.nextElement();
				Enumeration<InetAddress> inteAddresses = netInterface.getInetAddresses();
				ips = getIps(inteAddresses);
			}
		} catch (SocketException ex) {
			logger.error(ex.getMessage(), ex);
		}
		return ips;
	}

	private static List<String> getIps(Enumeration<InetAddress> inteAddresses) {
		List<String> ips = new ArrayList<>();
		while (inteAddresses.hasMoreElements()) {
			InetAddress inetAddress = inteAddresses.nextElement();
			if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
				ips.add(inetAddress.getHostAddress());
			}
		}
		return ips;
	}

	private static String collectionToDelimitedString(Collection<String> coll, String delim) {
		if (coll == null || coll.isEmpty()) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		Iterator<?> it = coll.iterator();
		while (it.hasNext()) {
			sb.append(it.next());
			if (it.hasNext()) {
				sb.append(delim);
			}
		}
		return sb.toString();
	}

	/**
	 * 获取当前机器的hostname
	 * @return
	 */
	public static String getHostName() {
		String hostName = null;
		try {
			hostName = InetAddress.getLocalHost().getHostName();
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		return hostName;
	}

	/**
	 * 获取客户端的真实ip
	 */
	public static String getClientRealIp(HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");
		if (StringUtils.isEmpty(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = getLocalIpAddress(request);
		}

		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15 && ipAddress.indexOf(',') >= 0) {
			ipAddress = ipAddress.substring(0, ipAddress.indexOf(','));
		}
		return ipAddress;
	}

	private static String getLocalIpAddress(HttpServletRequest request) {
		String ipAddress = request.getRemoteAddr();
		if (ipAddress.equals("127.0.0.1")) {
			// 根据网卡取本机配置的IP
			InetAddress inet = null;
			try {
				inet = InetAddress.getLocalHost();
				if (inet != null) {
					ipAddress = inet.getHostAddress();
				}
			} catch (UnknownHostException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return ipAddress;
	}

	/**
	 * 取到当前机器的IP地址
	 */
	public static String getHostIp() {
		List<String> ips = new ArrayList<>();
		Enumeration<NetworkInterface> netInterfaces = null;

		try {
			netInterfaces = NetworkInterface.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = netInterfaces.nextElement();
				Enumeration<InetAddress> inteAddresses = netInterface.getInetAddresses();
				while (inteAddresses.hasMoreElements()) {
					InetAddress inetAddress = inteAddresses.nextElement();
					if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
						ips.add(inetAddress.getHostAddress());
					}
				}
			}
		} catch (SocketException ex) {
			logger.error(ex.getMessage(), ex);
		}

		return collectionToDelimitedString(ips, ",");
	}
	
	/**
	 * 提取URL里的域名
	 */
	public static String getDomain(String url) {
		if(StringUtils.isEmpty(url)) {
			return null;
		}
		
		if(url.indexOf("localhost")>-1) {
			return "localhost";
		}
		
		try {
			Pattern p = Pattern.compile("[^//]*$?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE);
			Matcher matcher = p.matcher(url);
			matcher = p.matcher(url);
			matcher.find();
			return matcher.group();
		} catch (Exception ex) {
			logger.error("getDomain | 从url里获取域名错误。url：{}", url);
			// 未匹配上域名，则提取url里的ip
			return getDomainOrIp(url);
		}
	}
	
	/**
	 * 提取URL里的域名或IP
	 */
	public static String getDomainOrIp(String url) {
		if(StringUtils.isEmpty(url)) {
			return null;
		}
		
		try {
			return new URL(url).getHost();
		} catch (Exception ex) {
			logger.error("getDomainOrIp | 从url里获取域名或IP错误。url：{}", url);
			return "";
		}
	}
	
	/**
	 * 从url里提取协议头+域名+端口号
	 * @throws MalformedURLException 
	 */
	public static String getProtocolAndDomainAndPort(String longUrl) throws MalformedURLException {
		if(StringUtils.isEmpty(longUrl)) {
			return null;
		}
		
		String result = "";
		
		URL url = new URL(longUrl);
		String protocol = url.getProtocol();
		String host = url.getHost();
		int port = url.getPort();
		if(port==-1) {
			result = protocol+"://"+host;
		} else {
			result = protocol+"://"+host+":"+port;
		}
		
		return result;
	}

	/**
	 * main
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Ip:" + getIp());
		System.out.println("hostIp:" + getHostIp());
		String url = "http://47.75.126.121:8090/ank_admin/testProp";
		System.out.println(getDomain(url));
		System.out.println(getDomainOrIp(url));
	}

}
